import { defineStore } from 'pinia'

interface Todo {
  id: number
  content: string
  done: boolean
}
const useTodosStore = defineStore('todos', {
  // 状态
  state() {
    return {
      list: JSON.parse(localStorage.getItem('todos-list') || '[]') as Todo[],
    }
  },
  // 计算
  getters: {
    isCheckAll(): boolean {
      return this.list.length > 0 && this.list.every((v) => v.done)
    },
  },
  // 函数
  actions: {
    // 修改任务状态
    changeDone(id: number) {
      const todo = this.list.find((v) => v.id === id)
      if (todo) {
        todo.done = !todo.done
      }
    },
    // 删除任务
    delTodo(id: number) {
      this.list = this.list.filter((v) => v.id !== id)
    },
    // 添加任务
    addTodo(content: string) {
      this.list.unshift({
        id: Date.now(),
        content: content,
        done: false,
      })
    },
    // 修改全选
    changeCheckAll(isCheckAll: boolean) {
      this.list.forEach((item) => {
        item.done = isCheckAll
      })
    },
  },
})

export default useTodosStore
